#!/usr/bin/env python
# -*- coding: utf-8 -*-
# title       :
# author      : jarry

import sys
import os
import logging
from SceneCheckTool.checkScript.CheckBase import CheckBase

try:
    import maya.cmds as cmds
    import pymel.core as pm
    import jarryLibs.mayakit.MayaUtils as mu
    reload(mu)
except:
    pass

logging.basicConfig()
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)


class CtrlE16Value(CheckBase):
    def __init__(self):
        super(CtrlE16Value, self).__init__()
        pass

    def init_file(self):
        import elsLibs.AssetInfoFromFile as elsaif
        reload(elsaif)
        current_file = mu.sceneName()
        aif = elsaif.AssetInfoFromFile(current_file)
        self.asset_name = aif.get_name
        self.shortType = aif.get_shortType
        self.step = aif.get_step


    def get_all_ctrl(self):
        top_set = 'All_ctrls'
        exclude_set_list = [u'facial_ctrls']
        exculde_ctrl_list = [u'Master_ctrl', u'Local_ctrl', u'Root_ctrl', u'Main', u'M_Local_ctrl', u'Visibility']
        exculde_attr_list = ['visibility', 'rotationOrder', '_', '__', '___', '____', '_____']
        exculde_attrtype_list = ['char', 'string', 'bool']
        ns = ''
        if ns:
            top_set = '%s:%s' % (ns, top_set)
            exclude_set_list = ['%s:%s' % (ns, n) for n in exclude_set_list]
            exculde_ctrl_list = ['%s:%s' % (ns, n) for n in exculde_ctrl_list]

        ctrl_set_list = cmds.ls(top_set, type='objectSet')
        if not ctrl_set_list:
            return
        # 得到所有有效sets
        top_ctrl_set = ctrl_set_list[0]
        child_set_list = cmds.sets(top_ctrl_set, q=1, no=1)
        tpose_set_list = list(set(child_set_list) - set(exclude_set_list))
        tpose_set_list.append(top_ctrl_set)
        # 得到所有有效控制器
        ctrl_list = []
        for st in tpose_set_list:
            if not cmds.objectType(st) == 'objectSet':
                continue
            node_list = cmds.sets(st, q=1, no=1)
            if node_list:
                for node in node_list:
                    if cmds.objectType(node) == 'nurbsCurve':
                        ctrl_list.append(cmds.listRelatives(node, p=1)[0])
                    elif cmds.objectType(node) == 'transform' or cmds.objectType(node) == 'joint':
                        try:
                            if cmds.objectType(cmds.listRelatives(node, s=1)[0]) == 'nurbsCurve':
                                ctrl_list.append(node)
                        except:
                            pass

        ctrl_list = list(set(ctrl_list) - set(exculde_ctrl_list))
        return ctrl_list

    def check_error(self, ctrl, fix=False):
        #
        error_list = []
        cbx_key_dict = {0: ['tx', 'ty', 'tz', 'rx', 'ry', 'rz'], 1: ['sx', 'sy', 'sz']}

        for dv in cbx_key_dict:
            cbx_list = cbx_key_dict[dv]
            for k in cbx_list:
                key_name = '%s.%s' % (ctrl, k)
                if not cmds.getAttr(key_name, l=1):
                    v = cmds.getAttr(key_name)
                    if 'e-' in str(v):
                        if fix:
                            cmds.setAttr(key_name, dv)
                        error_list.append(ctrl)
                    else:
                        if fix:
                            if cmds.listConnections(key_name, d=False, s=True) or cmds.getAttr(key_name, l=True):
                                continue
                            if 't' in k:
                                if cmds.listConnections('%s.t' % ctrl, d=False, s=True):
                                    continue
                            elif 'r' in k:
                                if cmds.listConnections('%s.r' % ctrl, d=False, s=True):
                                    continue
                            elif 's' in k:
                                if cmds.listConnections('%s.s' % ctrl, d=False, s=True):
                                    continue
                            cmds.setAttr(key_name, float(str(v)))
        return error_list

    def check(self):
        current_file = mu.sceneName()
        if not current_file:
            result_log = u'Error: 当前文件未保存!'
            return result_log
        try:
            self.init_file()
        except:
            result_log = u'Error:当前文件不符合ELS项目资产文件命名规则'
            return result_log
        if self.shortType in ['c', 'p']:
            render_mod = 'Root_Grp|mod_grp|%s_%s_render_grp' % (self.shortType, self.asset_name)
            if not cmds.objExists(render_mod):
                result_log = u'Error:不存在这个资产对应的组: %s\n' % render_mod
                return result_log
        if self.step == 'rig':
            rig_grp = 'Root_Grp|rig_grp'
            if not cmds.objExists(rig_grp):
                result_log = u'Error:不存在这个资产对应的组: %s\n' % rig_grp
                return result_log
        else:
            result_log = u'Error:当前文件不符合ELS项目rig资产文件命名规则'
            return result_log
        all_ctrl = self.get_all_ctrl()
        error_list = []
        if not all_ctrl:
            result_log = u'Error:没有查询到符合规则的控制器'
            return result_log
        for ctrl in all_ctrl:
            error_list += self.check_error(ctrl)
        if error_list:
            result_log = u'Error: %s' % error_list
        else:
            result_log = u'Succeed:没有问题'
        return result_log

    def fix(self):
        all_ctrl = self.get_all_ctrl()
        error_list = []
        if not all_ctrl:
            result_log = u'Error:没有查询到符合规则的控制器'
            return result_log
        for ctrl in all_ctrl:
            error_list += self.check_error(ctrl, fix=True)

        result_log = u'Succeed:修复成功%s' % error_list
        return result_log
